package com.egao.common.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.core.damon.constant.UserConstant;
import com.egao.common.core.damon.results.PageResult2;
import com.egao.common.core.damon.utils.StringUtil;
import com.egao.common.core.exception.BusinessException;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.system.biz.UserBiz;
import com.egao.common.system.entity.Menu;
import com.egao.common.system.entity.Role;
import com.egao.common.system.entity.User;
import com.egao.common.system.entity.UserRole;
import com.egao.common.system.mapper.MenuMapper;
import com.egao.common.system.mapper.UserMapper;
import com.egao.common.system.mapper.UserRoleMapper;
import com.egao.common.system.service.UserService;
import com.egao.gps.entity.UserLoginTimes;
import com.egao.gps.service.UserLoginTimesService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户服务实现类
 * Created by wangfan on 2018-12-24 16:10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private UserBiz userBiz;
    @Autowired
    private UserLoginTimesService userLoginTimesService;

    @Override
    public User getByUsername(String username) {
        return baseMapper.selectOne(new QueryWrapper<User>().eq("username", username));
    }

    @Override
    public User getFullById(Integer userId) {
        List<User> userList = baseMapper.listAll(new PageParam<User>().put("userId", userId).getNoPageParam());
        if (userList == null || userList.size() == 0) return null;
        return selectRoleAndAuth(userList.get(0));
    }

    @Override
    public User selectRoleAndAuth(User user) {
        if (user == null) return user;
        user.setRoles(userRoleMapper.listByUserId(user.getUserId()));
        return selectUserAuth(user);
    }

    @Override
    public User selectUserAuth(User user) {
        if (user == null) return user;
        List<Menu> menus = menuMapper.listByUserId(user.getUserId(), null);
        List<Menu> authList = new ArrayList<>();
        for (Menu menu : menus) {
            if (StrUtil.isNotBlank(menu.getAuthority())) {
                authList.add(menu);
            }
        }
        user.setAuthorities(authList);
        return user;
    }

    @Override
    public PageResult<User> listPage(PageParam<User> page) {
        List<User> users = baseMapper.listPage(page);
        // 查询用户的角色
        selectUserRoles(users);
        return new PageResult<>(users, page.getTotal());
    }

    @Override
    public List<User> listAll(Map<String, Object> page) {
        List<User> users = baseMapper.listAll(page);
        // 查询用户的角色
        selectUserRoles(users);
        return users;
    }

    @Transactional
    @Override
    public boolean saveUser(User user) {
        if (user.getUsername() != null && baseMapper.selectCount(new QueryWrapper<User>()
                .eq("username", user.getUsername())) > 0) {
            throw new BusinessException("账号已存在");
        }
        if (user.getPhone() != null && baseMapper.selectCount(new QueryWrapper<User>()
                .eq("phone", user.getPhone())) > 0) {
            throw new BusinessException("手机号已存在");
        }
        if (user.getEmail() != null && baseMapper.selectCount(new QueryWrapper<User>()
                .eq("email", user.getEmail())) > 0) {
            throw new BusinessException("邮箱已存在");
        }
        boolean result = baseMapper.insert(user) > 0;
        if (result) {
            addUserRoles(user.getUserId(), user.getRoleIds(), false);
        }
        return result;
    }

    @Transactional
    @Override
    public boolean updateUser(User user) {
        if (user.getUsername() != null && baseMapper.selectCount(new QueryWrapper<User>()
                .eq("username", user.getUsername()).ne("user_id", user.getUserId())) > 0) {
            throw new BusinessException("账号已存在");
        }
        if (user.getPhone() != null && baseMapper.selectCount(new QueryWrapper<User>()
                .eq("phone", user.getPhone()).ne("user_id", user.getUserId())) > 0) {
            throw new BusinessException("手机号已存在");
        }
        if (user.getEmail() != null && baseMapper.selectCount(new QueryWrapper<User>()
                .eq("email", user.getEmail()).ne("user_id", user.getUserId())) > 0) {
            throw new BusinessException("邮箱已存在");
        }
        boolean result = baseMapper.updateById(user) > 0;
        if (result) {
            addUserRoles(user.getUserId(), user.getRoleIds(), true);
        }
        return result;
    }

    @Transactional
    @Override
    public boolean updateUser2(User user, User loginUser) {
        addUserRoles(user.getUserId(), user.getRoleIds(), true);
        return true;
    }

    @Override
    public boolean comparePsw(String dbPsw, String inputPsw) {
        return dbPsw != null && new BCryptPasswordEncoder().matches(inputPsw, dbPsw);
    }

    @Override
        public String encodePsw(String psw) {
            if (psw == null) return null;
            return new BCryptPasswordEncoder().encode(psw);
    }

    public static void main(String[] args) {
        UserServiceImpl u = new UserServiceImpl();
        System.out.println(u.encodePsw("123"));
    }

    /**
     * 批量查询用户的角色
     */
    private void selectUserRoles(List<User> users) {
        if (users != null && users.size() > 0) {
            List<Integer> userIds = new ArrayList<>();
            for (User one : users) {
                userIds.add(one.getUserId());
            }
            List<Role> userRoles = userRoleMapper.listByUserIds(userIds);
            for (User user : users) {
                List<Role> roles = new ArrayList<>();
                for (Role userRole : userRoles) {
                    if (user.getUserId().equals(userRole.getUserId())) {
                        roles.add(userRole);
                    }
                }
                user.setRoles(roles);
            }
        }
    }

    /**
     * 添加用户角色
     */
    private void addUserRoles(Integer userId, List<Integer> roleIds, boolean deleteOld) {
        if (deleteOld) {
            userRoleMapper.delete(new UpdateWrapper<UserRole>().eq("user_id", userId));
        }
        if (userRoleMapper.insertBatch(userId, roleIds) < roleIds.size()) {
            throw new BusinessException("操作失败");
        }
    }

    @Override
    public User getUserByUsername(User user) {
        return userBiz.getUserByUsername(user);
    }

    @Override
    public List<User> getGzhIdsByUserId(User user) {
        return userBiz.getGzhIdsByUserId(user);
    }

    @Override
    public List<Role> getRoleIdsByUserId(User user) {
        return userBiz.getRoleIdsByUserId(user);
    }

    @Override
    public Integer apiSave(User user) {
        return userBiz.apiSave(user);
    }

    @Override
    public JsonResult apiSave2(User user) throws Exception{
        if(StringUtil.isBlank(user.getUsername(), user.getPassword(),user.getPhone(),user.getNickName())
                || user.getRoleIds()==null || user.getRoleIds().size() ==0
        ){
            return JsonResult.error("请把信息填写完整!");
        }
        user.setState("0");
        user.setOrganizationId(UserConstant.ORGANIZATION_ID);
        user.setType("平台用户");
        user.setAdmin("0");
        user.setPasswordorigin(user.getPassword());
        user.setPassword(encodePsw(user.getPassword()));
        int id= userBiz.apiSave(user);
        user.setUserId(id);
        for (int i : user.getRoleIds()) {
            user.setRoleId(i);
            userBiz.saveUserRole(user);
        }
        return JsonResult.ok("添加成功");
    }

    @Override
    public JsonResult saveCustomerStaff(User user) throws Exception{
        if(StringUtil.isBlank(user.getUsername(),user.getNickName(), user.getPassword(), user.getPhone(),user.getCustomerId()+"")
        ){
            return JsonResult.error("请把信息填写完整!");
        }
        user.setState("0");
        user.setOrganizationId(UserConstant.ORGANIZATION_ID);
        user.setType("货代");
        user.setAdmin("0");
        user.setPasswordorigin(user.getPassword());
        user.setPassword(encodePsw(user.getPassword()));
        int id= userBiz.apiSave(user);
        user.setUserId(id);
        user.setRoleId(UserConstant.CUSTOMER_STAFF_ROLE_ID);
        userBiz.saveUserRole(user);
        return JsonResult.ok("添加成功");
    }

    @Override
    public boolean saveUserRole(User user) {
        return userBiz.saveUserRole(user);
    }

    @Override
    @Transactional
    public boolean removeUser(User user, User loginUser) {
        userBiz.removeUserRoleAll(user);
        return userBiz.removeUser(user,loginUser);
    }
    @Override
    public boolean removeUserRole(User user) {
        return userBiz.removeUserRole(user);
    }
    @Override
    public boolean removeRoleAll(User user) {
        return userBiz.removeUserRoleAll(user);
    }

    @Override
    public boolean apiExamine(User user, User loginUser) {
        return userBiz.apiExamine(user, loginUser);
    }

    @Override
    public User apiGetByUsername(String username) {
        return userBiz.apiGetByUsername(username);
    }
    @Override
    public User apiGetByCustomerId(String id, String type) {
        return userBiz.apiGetByCustomerId(id, type);
    }

    @Override
    public boolean apiSetCustomerId(User user, User loginUser) {
        return userBiz.apiSetCustomerId(user, loginUser);
    }

    @Override
    public JsonResult updatePsw(User user, User loginUser) {
        if (userBiz.updatePsw(user, loginUser)) {
            return JsonResult.ok("密码修改成功");
        }
        return JsonResult.error("密码修改失败");
    }

    @Override
    public User getUserByPhone(User user) {
        return userBiz.getUserByPhone(user);
    }

    @Override
    public User getUserById(User user) {
        return userBiz.getUserById(user);
    }

    @Override
    public List<Menu> apiGetMenuByUser(User user) {
        return userBiz.apiGetMenuByUser(user);
    }

    @Override
    public JsonResult list(PageResult2<T> page, User user, User loginUser)  throws Exception{
        try {
            JsonResult jr = userBiz.list(page,user,loginUser);
            List<User> userList = (List<User>)jr.getData();
            for (User user3: userList) {
                user3.setRoles(userBiz.getRoleIdsByUserId(user3));
            }
            return jr;
        } catch (Exception e) {
            throw new Exception("查询错误,请联系平台管理员!");
        }
    }

    @Override
    public JsonResult md5Phone(PageResult2<T> page, User user, User loginUser)  throws Exception{
        try {
            JsonResult jr = userBiz.list(page,user,loginUser);
//            List<User> userList = (List<User>)jr.getData();
//            for (User user3: userList) {
//                user3.setPhone(user3.getPhone2());
//                userBiz.updateUser(user3,loginUser);
//            }
            return jr;
        } catch (Exception e) {
            throw new Exception("查询错误,请联系平台管理员!");
        }
    }

    @Override
    public JsonResult platPage(PageResult2<T> page, User user, User loginUser)  throws Exception{
        try {
            if(loginUser.getType().equals("平台用户")){
                user.setType("平台用户");
                user.setOrganizationId(1);
                JsonResult jr = userBiz.list(page,user,loginUser);
                List<User> userList = (List<User>)jr.getData();
                for (User user3: userList) {
                    user3.setRoles(userBiz.getRoleIdsByUserId(user3));
                }
                return jr;
            } else if(loginUser.getType().equals("货代")){
                user.setCustomerId(loginUser.getCustomerId());
                if(user.getCustomerId()==null || user.getCustomerId()==0){
                    return JsonResult.error("没有货代id");
                }
                user.setType("货代");
                JsonResult jr = userBiz.list(page,user,loginUser);
                List<User> userList = (List<User>)jr.getData();
                for (User user3: userList) {
                    user3.setRoles(userBiz.getRoleIdsByUserId(user3));
                }
                return jr;
            }
            return null;
        } catch (Exception e) {
            throw new Exception("查询错误,请联系平台管理员!");
        }
    }
    @Override
    public JsonResult customerPage(PageResult2<T> page, User user, User loginUser)  throws Exception{
        try {
            if(user.getCustomerId()==null || user.getCustomerId()==0){
                return JsonResult.error("没有货代id");
            }
            user.setType("货代");
            JsonResult jr = userBiz.list(page,user,loginUser);
            List<User> userList = (List<User>)jr.getData();
            for (User user3: userList) {
                user3.setRoles(userBiz.getRoleIdsByUserId(user3));
            }
            return jr;
        } catch (Exception e) {
            throw new Exception("查询错误,请联系平台管理员!");
        }

    }

    @Override
    public JsonResult updateUser(User user, User loginUser) {
        if(user.getUserId() == null || StringUtil.isBlank(user.getNickName(),user.getPhone())) {
            return JsonResult.error("请填写完整的内容,操作失败!");
        }
        userBiz.updateUser(user, loginUser);

        return JsonResult.ok("修改成功");
    }

    @Override
    public JsonResult updateUserState(User user, User loginUser) {
        if(userBiz.updateUserState(user, loginUser)){
            UserLoginTimes userLoginTimes = new UserLoginTimes();
            userLoginTimes.setUsername(user.getUsername());
            userLoginTimesService.thaw(userLoginTimes);
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }

    @Override
    public JsonResult updateGzhId(User user) {
        userBiz.updateGzhId(user);
        return JsonResult.ok("公众号绑定成功");
    }

    @Override
    public JsonResult remove(User user, User loginUser) {
        if (userBiz.remove(user, loginUser)) {
            return JsonResult.ok("删除成功");
        }
        return JsonResult.error("删除失败");
    }

}
